package Engine.Sound;

import java.io.File;
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

import Engine.Utils.Vector2f;

/**
 * 
 * @author Lueko
 *
 */
public class Sound {

	private Clip clip;
    private AudioInputStream ais;
    private FloatControl volume;
    private FloatControl pan;
    private Vector2f pos;
    private String name;
    
    public Sound(File soundFile, Vector2f pos, String name) {
    	this.pos = pos;
    	this.name = name;
    	open(soundFile);
    }
    
    public void open(File soundFile) {
    	if (soundFile.exists()) {
            try {
                clip = AudioSystem.getClip();
                ais = AudioSystem.getAudioInputStream(soundFile);
                clip.open(ais);
                volume = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
                pan = (FloatControl) clip.getControl(FloatControl.Type.PAN);
            } catch (LineUnavailableException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (UnsupportedAudioFileException e) {
                e.printStackTrace();
            }
        }
    }
    
    public void close() {
    	clip.close();
	}
    
    public void play() {
        clip.setFramePosition(0);
        clip.start();
    }
    
    public void loop(int count) {
    	clip.setFramePosition(0);
    	clip.loop(count);
    }
    
    public void stop() {
    	clip.stop();
    }
    
    public boolean isRunning() {
    	return clip.isRunning();
    }
    
    public void setVolume(float value) {
    	volume.setValue(value);
    }
    
    public void setPan(float value) {
    	pan.setValue(value);
    }
    
    public Clip getClip() {
    	return clip;
    }
    
    public FloatControl getVolume() {
    	return volume;
    }
    
    public FloatControl getPan() {
    	return pan;
    }
    
    public Vector2f getPos() {
    	return pos;
    }
    
    public String getName() {
    	return name;
    }
	
}
